package leetcode_100;

/**
 *@author 周杨
	SearchforARange Given an array of integers sorted in ascending order, find the starting and ending position of a given target value.
	
	Your algorithm's runtime complexity must be in the order of O(log n).
	
	If the target is not found in the array, return [-1, -1].
	
	For example,
	Given [5, 7, 7, 8, 8, 10] and target value 8,
	return [3, 4].
 *describe:分治法二分搜索数组 时间复杂度O(logN)
 *2018年4月13日 上午10:26:39
 */
public class SearchforARange_34 {

	public static void main(String[] args) {
		int nums[]=new int[] {5, 7, 7, 8, 8, 10};
		int nums1[]= new int[]{2,2};
		int nums2[]=new int[] {1,1,2};
		int res[]=searchRange(nums2,1);
		for(int i:res)
			System.out.println(i);

	}
	
	public static int[] searchRange(int[] nums, int target) {
        if(nums.length==0)
        	return new int[] {-1,-1};
        return help(nums,0,nums.length-1,target);
    }
	
	public static int[] help(int nums[],int l,int r,int target) {
		if(l>=r&&nums[l]!=target)
			return new int[] {-1,-1};
		int m=(r+l)/2;
		if(nums[m]==target) {
			int start=m,end=m,i=1;
			while(start-i>=0&&nums[start-i]==target) 
				start-=i;
			i=1;
			while(end+i<nums.length&&nums[end+i]==target)
				end+=i;
			return new int[] {start,end};
		}
		else  {
			int res[]= help(nums,l,m-1,target);
			if(res[0]==-1)
				return help(nums,m+1,r,target);
			else
				return res;
		}

			
	}

}
